package com.jfinal.weixin.controller;

import com.jfinal.core.Controller;
import com.jfinal.weixin.model.Menu;
import com.jfinal.weixin.model.WeixinInfo;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;

/**
 * Created by chengzhichao on 16/5/4.
 */

public class MenuController extends Controller {

    public ApiConfig getApiConfig() {
        ApiConfig ac = new ApiConfig(WeixinInfo.dao.getWeixinInfoById(1));
        return ac;
    }

    /**
     * 上传数据库中拼凑好的menuStr到微信服务器
     */
    public void postMenu() {
        int id = getParaToInt("menuid");
        String menuStr = Menu.dao.findById(id).getStr("menu_str");
        ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
        ApiResult apiResult = MenuApi.createMenu(menuStr);
        if (apiResult.isSucceed())
            renderText("菜单更新成功");
        else
            renderText(apiResult.getErrorMsg());
    }

    public void getMenu() {
        ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
        ApiResult apiResult = MenuApi.getMenu();
        if (apiResult.isSucceed())
            renderJson(apiResult.getJson());
        else
            renderJson(apiResult.getErrorMsg());
    }

    public void getMenuById() {
        int id = getParaToInt("menuid");
        Menu menu = Menu.dao.getMenuById(id);
        renderText(menu.getStr("menu_str").toString());
    }

    public void index(){
        render("/_back/menu/index.html");
    }

}
